﻿using AutoMapper;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using S.Organization.Read.API.Application.Command.SheepFarmCommand;
using S.Organization.Domian.Model;
using S.Organization.Infrastructure;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory; 
using PublicClass;

namespace S.Organization.Read.API.Application.CommandHandler.SheepFarmCommandHandler
{
    public  class GetSheepFarmCommandHandler : IRequestHandler<GetSheepFarmCommand, PageInfo<SheepFarmSetting>>
    {
        private readonly IBaseRepository<SheepFarmSetting> _repository;


        public GetSheepFarmCommandHandler(IBaseRepository<SheepFarmSetting> repository)
        {
            _repository = repository; 
        }

        public async Task<PageInfo<SheepFarmSetting>> Handle(GetSheepFarmCommand request, CancellationToken cancellationToken)
        {
            var query =  await _repository.AllAsync();
            //数据总条数
            int Count = query.Count();
            //总页数
            int Total = (int)Math.Ceiling(Count*1.0/(request.Size));
            if (!string.IsNullOrEmpty(request.FarmName))
            {
                query = query.Where(x => x.FarmName.Contains(request.FarmName));
            }

            if (!string.IsNullOrEmpty(request.Principal))
            {
                query = query.Where(x => x.Principal == request.Principal);
            }

            var list = query.Skip((request.Index-1)*request.Size).Take(request.Size);
            var res=list.OrderByDescending(x=>x.SheepFarmId).ToList();


            PageInfo<SheepFarmSetting> pageinfo = new PageInfo<SheepFarmSetting>();
            pageinfo.totalCount=Total;
            pageinfo.pageCount= Count;
            pageinfo.datas = res;
            return pageinfo;
        }
    }
}
